package com.example.demo.service;

/**
 * @Author YanJiaJian
 * @Date 2018/1/16 10:38
 */
public class ThreadTest {
    private static int number = 0;

    private static int catCount = 0;
    private static int dogCount = 0;

    private static final int amount = 500;

    public static volatile boolean exit = false;

    private static synchronized void eat() {
        number++;
    }

    private static class CatThread extends Thread {
        @Override
        public void run() {
            while (number < amount) {
                eat();
                System.out.println("猫吃掉了第" + number + "个饼");
                catCount++;
            }
        }
    }

    private static class DogThread extends Thread {
        @Override
        public void run() {
            while (number < amount) {
                eat();
                System.out.println("狗吃掉了第" + number + "个饼");
                dogCount++;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        CatThread cat = new CatThread();
        cat.start();
        DogThread dog = new DogThread();
        dog.start();
        cat.join();
        dog.join();
        if (dogCount + catCount != amount) {
            throw new RuntimeException("线程出错");
        }
        System.out.println("猫一共吃掉" + catCount + "个");
        System.out.println("狗一共吃掉" + dogCount + "个");

    }
}
